package nancal.mp.db.mongo.extend

import nancal.mp.db.mongo.entity.dev.AppDeploySetting
import nancal.mp.db.mongo.mor
import nancal.mp.db.mongo.table.DevGroup
import nbcp.base.comm.MemoryCacheList
import nbcp.base.extend.AsString
import nbcp.base.extend.must
import nbcp.myoql.db.mongo.query


/**
 * 获取部署环境。
 * @param envCode: 如果为空，则获取当前环境
 * @remark: 当切换激活项的时候，需要破坏 @current@ 缓存！
 */
fun DevGroup.AppDeploySettingEntity.getAppDeploySetting(envCode: String = ""): AppDeploySetting {
    var envName = envCode.AsString("@current@")
    val cacheKey = mor.dev.appDeploySetting.userDefineTableName + "." + envName

    var appDeploySetting = MemoryCacheList.expireAfterWrite30Secondes.get(cacheKey) {

        if (envCode.isEmpty()) {
            val list = mor.dev.appDeploySetting
                    .query()
                    .orderByDesc { it.isActive }
                    .limit(0, 2)
                    .toList();

            if (list.filter { it.isActive }.size == 2) {
                throw RuntimeException("appDeploySetting 存在多条 激活项")
            }

            return@get list.first()
        }

        val entity = mor.dev.appDeploySetting
                .query()
                .where { it.code mongoEquals envCode }
                .toEntity()
                .must()
                .elseThrow { "找不到 ${envCode} 的部署设置！" }

        return@get entity
    }

    return appDeploySetting as AppDeploySetting
}


